<template>
  <div v-if="editOpen">
    <t-dialog
      :header="header"
      :visible.sync="visible"
      :onClose="onClose"
      width="80%"
      top="5%"
      :closeOnOverlayClick="false"
    >
      <div style="height: 65vh">
        <div v-if="rowIndex==null">
          <t-alert style="margin-bottom: 20px" theme="info" :message="`当前页面可重复添加。目前已添加数量: ${data.length}`"/>
        </div>
        <t-form :disabled="disabled" :colon="true" ref="form" resetType="initial" :data="formData" labelWidth="160px"
                :rules="rules">
          <t-row style="row-gap:24px">
            <t-col :span="12">
              <t-form-item label="研究成果类型" name="expectResultType">
                <t-cascader :keys="{value:'id',label: 'name'}" clearable filterable
                            v-model="formData.expectResultType"
                            :options="menuOptions">
                </t-cascader>
              </t-form-item>
            </t-col>
            <t-col :span="12">
              <t-divider style="margin: 0;width: 200px;font-weight: bold">标题/作者/说明/排名</t-divider>
            </t-col>
            <t-col :span="6">
              <t-form-item label="标题" name="title">
                <t-input style="width:390px" v-model="formData.title"></t-input>
              </t-form-item>
            </t-col>
            <t-col :span="6">
              <t-form-item label="作者" name="authors">
                <!--                <t-input style="width:390px" v-model="formData.author"></t-input>-->
                <t-select v-model="formData.authors" @create="createOptions"
                          creatable
                          filterable :options="options1" multiple/>
              </t-form-item>
            </t-col>
            <t-col :span="6">
              <t-form-item label="说明" name="note">
                <t-input style="width:390px" v-model="formData.note"></t-input>
              </t-form-item>
            </t-col>
            <t-col :span="6">
              <t-form-item label="排名" name="level">
                <t-input-number :allowInputOverLimit="false" clearable v-model="formData.level"
                                :min="0"
                                placeholder="请输入"></t-input-number>
              </t-form-item>
            </t-col>
            <t-col :span="12">
              <t-divider style="margin: 0;width: 200px;font-weight: bold">期刊影响因子/奖类型</t-divider>
            </t-col>
            <t-col :span="6">
              <t-form-item label="期刊影响因子" name="impactFactor">
                <t-input style="width:390px" v-model="formData.impactFactor"></t-input>
              </t-form-item>
            </t-col>
            <t-col :span="6">
              <t-form-item label="奖类型" name="awardType">
                <t-input style="width:390px" v-model="formData.awardType"></t-input>
              </t-form-item>
            </t-col>
            <t-col :span="12">
              <t-divider style="margin: 0;width: 200px;font-weight: bold">是否高被引论文/奖等级</t-divider>
            </t-col>
            <t-col :span="6">
              <t-form-item label="是否高被引论文" name="isHighThesis">
                <t-switch
                  size="large"
                  v-model="formData.isHighThesis"
                  :label="['是', '否']"
                  :customValue="['1', '0']"
                ></t-switch>
              </t-form-item>
            </t-col>
            <t-col :span="6">
              <t-form-item label="奖等级" name="awardLevel">
                <t-input-number :allowInputOverLimit="false" clearable v-model="formData.awardLevel"
                                :min="0"
                                placeholder="请输入"></t-input-number>
              </t-form-item>
            </t-col>
          </t-row>
        </t-form>
      </div>
      <template #footer>
        <t-button theme="default" @click="onClose">取消</t-button>
        <t-button theme="primary" @click="onSubmit(1)">保存</t-button>
        <t-button theme="primary" @click="onSubmit(2)">保存并继续添加</t-button>
      </template>
    </t-dialog>
    <t-table bordered :selected-row-keys="selectedRowKeys"
             @select-change="(val)=>{selectedRowKeys=val}" rowKey="id" :data="data"
             :columns="columns">
      <template #sort="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>
      <template #expectResultType="{ row, rowIndex }">
        {{ row.expectResultType | filterParentsByTree(menuOptions, "children","id","name") }}
      </template>
      <template #isHighThesis="{ row, rowIndex }">
        {{ row.isHighThesis === '1' ? '是' : '否' }}
      </template>
      <template #empty>
        <span>暂无数据 请点击新增按钮</span>
      </template>
    </t-table>
    <div style="margin-top: 10px" class="btn-group-inline">
      <t-button @click="addData">新增</t-button>
      <t-button @click="upData">上移</t-button>
      <t-button @click="downData">下移</t-button>
      <t-button @click="updateData">修改</t-button>
      <t-button @click="delData">删除</t-button>
    </div>
  </div>
  <div v-else>
    <t-table rowKey="id" :data="data"
             :columns="columns2">
      <template #sort="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>
      <template #expectResultType="{ row, rowIndex }">
        {{ row.expectResultType | filterParentsByTree(menuOptions,"children","id","name") }}
      </template>
      <template #isHighThesis="{ row, rowIndex }">
        {{ row.isHighThesis === '1' ? '是' : '否' }}
      </template>
      <!--      <template #expectResultType="{ row, rowIndex }">-->
      <!--        <t-cascader filterable clearable :style="{color:diffData.length>=rowIndex+1 && diffData[rowIndex].expectResultType!==row.expectResultType?'red':''}" readonly :keys="{value:'id',label: 'name'}" v-model="row.expectResultType" :options="menuOptions"></t-cascader>-->
      <!--      </template>-->

      <!--      <template #count="{row, rowIndex}">-->
      <!--        <div v-if="row.quantization === '1'" :style="{color:diffData.length>=rowIndex+1 && diffData[rowIndex].count!==row.count?'red':''}"> {{ row.expectResultType !== 99 ? row.count : '' }}</div>-->
      <!--        <span v-else :style="{color:diffData.length>=rowIndex+1 && diffData[rowIndex].note!==row.note?'red':''}"> {{ row.note }}</span>-->
      <!--      </template>-->
    </t-table>
  </div>
</template>

<script>
export default {
  name: "item-approach-expectResults",
  dicts: ["expect_result_type"],
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    editOpen: {
      type: Boolean,
      default: false
    },
    projectId: [String, Number],
    disabled: {
      type: Boolean,
      default: false
    },
    oldData: {
      type: Array,
      default: () => [],
    },
    useOldData: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      projectLeaderName: "",
      options1: [],
      rowIndex: null,
      header: '添加',
      diffData: [],
      menuOptions: [],
      selectedRowKeys: [],
      dialogOpen: false,
      visible: false,
      formData: {
        expectResultType: null,
        title: '',
        author: '',
        authors: [],
        note: '',
        level: null,
        impactFactor: '',
        awardType: '',
        isHighThesis: '0',
        awardLevel: null,
      },
      rules: {
        expectResultType: [
          {
            required: true,
            message: "研究成果类型不能为空",
          }
        ],
      },
      data: [],
      columns: [
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          width: 64,
        },
        {
          colKey: 'sort',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: 'expectResultType',
          title: "研究成果类型",
          align: "center",
          width: 400
          // ellipsis: true,
        },
        {
          colKey: 'info_all',
          title: "标题/作者/说明/排名",
          align: "center",
          children: [
            {
              colKey: 'title',
              title: "标题",
              align: "center",
            },
            {
              colKey: 'author',
              title: "作者",
              align: "center",
            },
            {
              colKey: 'note',
              title: "说明",
              align: "center",
            },
            {
              colKey: 'level',
              title: "排名",
              align: "center",
            }
          ]
        },
        {
          colKey: 'qk_all',
          title: "期刊影响因子/奖类型",
          align: "center",
          children: [
            {
              colKey: 'impactFactor',
              title: "期刊影响因子",
              align: "center",
            },
            {
              colKey: 'awardType',
              title: "奖类型",
              align: "center",
            },
          ]
        },
        {
          colKey: 'gb_all',
          title: "是否高被引论文/奖等级",
          align: "center",
          children: [
            {
              colKey: 'isHighThesis',
              title: "是否高被引论文",
              align: "center",
            },
            {
              colKey: 'awardLevel',
              title: "奖等级",
              align: "center",
            },
          ]
        },
      ],
      columns2: [
        {
          colKey: 'sort',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: 'expectResultType',
          title: "研究成果类型",
          align: "center",
          width: 400
          // ellipsis: true,
        },
        {
          colKey: 'info_all',
          title: "标题/作者/说明/排名",
          align: "center",
          children: [
            {
              colKey: 'title',
              title: "标题",
              align: "center",
            },
            {
              colKey: 'author',
              title: "作者",
              align: "center",
            },
            {
              colKey: 'note',
              title: "说明",
              align: "center",
            },
            {
              colKey: 'level',
              title: "排名",
              align: "center",
            }
          ]
        },
        {
          colKey: 'qk_all',
          title: "期刊影响因子/奖类型",
          align: "center",
          children: [
            {
              colKey: 'impactFactor',
              title: "期刊影响因子",
              align: "center",
            },
            {
              colKey: 'awardType',
              title: "奖类型",
              align: "center",
            },
          ]
        },
        {
          colKey: 'gb_all',
          title: "是否高被引论文/奖等级",
          align: "center",
          children: [
            {
              colKey: 'isHighThesis',
              title: "是否高被引论文",
              align: "center",
            },
            {
              colKey: 'awardLevel',
              title: "奖等级",
              align: "center",
            },
          ]
        },
      ]
    }
  },
  watch: {
    value: {
      deep: true,
      immediate: true,
      handler(val) {
        if (val && val.length > 0 && this.useOldData) {
          let newArr = val.map(data => {
            return {
              ...data,
              authors: data.author.split(";").filter(item => item !== ''),
              initType: 'init'
            }
          })
          // 防止无限循环，简单比较一下
          if (JSON.stringify(val) !== JSON.stringify(this.data)) {
            this.data = newArr
          }
        }
      }
    },
    data: {
      deep: true,
      immediate: true,
      handler(val) {
        const newData = this.data.map((val, index) => ({
          ...val,
          sort: index + 1,
          author: val.authors.join(";"),
          projectId: Number(this.projectId)
        }))
        this.$emit("input", newData);
      }
    },
    projectId: {
      deep: true,
      immediate: true,
      handler(val) {
        if (val) {
          this.getData(val);
        }
      }
    },
    oldData: {
      deep: true,
      immediate: true,
      handler(val) {
        this.diffData = this.oldData;
      }
    },
  },
  async created() {

  },
  methods: {
    createOptions(value) {
      this.options1.push({
        value,
        label: value,
      });
    },
    onSubmit(type) {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {

          if (this.rowIndex !== null) {  // eslint-disable-line
            this.$set(this.data, this.rowIndex, {
              projectId: this.projectId,
              ...this.formData,
            })
            this.$message.success("修改成功");
            this.$refs.form.reset();
            this.dialogOpen = false;
            this.visible = false;
            this.rowIndex = null;
          } else {
            const newId = Number(new Date().getTime()) + Number(Math.random() * 10)
            this.data.push({
              ...this.formData,
              id: newId,
              projectId: this.projectId,
            })
          }
          this.$refs.form.reset();
          if (type === 1) {
            this.onClose()
          }
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      })
    },
    onClose() {
      this.$refs.form.reset();
      this.visible = false;
    },
    async getData() {
      this.$api.kjxm.project.get(this.projectId).then(response => {
        this.projectLeaderName = response.data.projectLeader.name;
      }).catch((e) => {
        this.applyLoading = false;
        this.$message.error(e.toString());
      });
      await Promise.all([this.getTreeSelect()]);
      // 显示外层带的数据不查询
      if (this.useOldData) {
        return false;
      }
    },
    addData() {
      if (this.projectLeaderName) {
        this.formData.authors = [this.projectLeaderName]
        this.options1 = [{label: this.projectLeaderName, value: this.projectLeaderName}]
      }
      this.rowIndex = null;
      this.dialogOpen = true;
      this.visible = true;
    },
    /** 查询菜单下拉树结构 */
    getTreeSelect() {
      return this.$api.kjxm.kpi.list().then(response => {
        this.menuOptions = this.handleTree(response.data, "id");
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    upData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[0].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是第一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index - 1)
      }
    },
    updateData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return false;
      }
      const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
      Object.assign(this.formData, this.data[index])
      this.options1 = this.formData.authors.map((val) => ({value: val, label: val}))
      this.rowIndex = index;
      this.header = "修改"
      this.dialogOpen = true;
      this.visible = true;
    },
    downData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[this.data.length - 1].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是最后一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index + 1)
      }
    },
    delData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
      this.data.splice(index, 1)
      this.selectedRowKeys = [];
    },
    moveInArray(arr, ffrom, to) {
      // 删除当前的位置
      const item = arr.splice(ffrom, 1);
      // 确保还剩有元素移动
      if (!item.length) {
        this.$message.warning(`There is no item in the array at index ${ffrom}`);
      }
      // 移动元素到指定位置
      arr.splice(to, 0, item[0]);
    },
  }
}
</script>

<style lang="less" scoped>
</style>
